package design2.iterator.example.social_networks;

import design2.iterator.example.iterators.LinkedInIterator;
import design2.iterator.example.iterators.ProfileIterator;
import design2.iterator.example.profile.Profile;

import java.util.ArrayList;
import java.util.List;

public class LinkedIn implements SocialNetwork{



	private List<Profile> contacts;

	public LinkedIn(List<Profile> contacts) {
		if(contacts!=null){
			this.contacts=contacts;
		}else{
			this.contacts = new ArrayList<>();
		}
	}

	@Override
	public ProfileIterator createFriendsIterator(String profileEmail) {
		return new LinkedInIterator(this,"friends",profileEmail);
	}

	@Override
	public ProfileIterator createCoworkersIterator(String profileEmail) {
		return  new LinkedInIterator(this,"coworkers",profileEmail);
	}

	public Profile requestProfileFromLinkedInAPI(String profileEmail){
		//这里有一个对Facebook API端点之一的POST请求。
		//相反，我们模拟长网络连接，这是您所期望的
		//在现实生活中。。。
		//TODO 拆分代码粒度更小，可重复使用
		simulateNetworkLatency();
		System.out.println("LinkedIn: Loading profile '" + profileEmail + "' over the network...");

		return  findContact(profileEmail);
	}


	public List<String> requestProfileFriendsFromLinkedInAPI(String profileEmail,String contactType){
		simulateNetworkLatency();
		System.out.println("LinkedIn: Loading '" + contactType + "' list of '" + profileEmail + "' over the network...");

		Profile profile=findContact(profileEmail);
		if(profile!=null){
			return profile.getContacts(contactType);
		}
		return null;
	}



	private Profile findContact(String profileEmail){
		for (Profile profile : contacts) {
			if(profile.getEmail().equals(profileEmail)){
				return profile;
			}
		}
		return null;
	}

	//模拟工作状态
	private void simulateNetworkLatency(){
		try {
			Thread.sleep(2500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
